package com.tanjie.blackbean.mybatis.support;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.tanjie.blackbean.core.web.BlackbeanRequestContextHolder;
import com.tanjie.blackbean.mybatis.common.CommonField;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * MybatisPlus 字段自动填充handler
 *
 * @author: tanjie
 * @date: 2021-11-23
 **/
@Slf4j
public class AutoFieldFillHandler implements MetaObjectHandler {

    @Override
    public boolean openInsertFill() {
        return MetaObjectHandler.super.openInsertFill();
    }

    @Override
    public boolean openUpdateFill() {
        return MetaObjectHandler.super.openUpdateFill();
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("MybatisPlus---新增insert字段自动填充---begin---");
        // 创建
        this.strictInsertFill(metaObject, CommonField.CREATE_TIME.getProperty(), Date.class, new Date());
        this.strictInsertFill(metaObject, CommonField.CREATE_BY.getProperty(), String.class, BlackbeanRequestContextHolder.getUserId());
        // 修改
        this.strictInsertFill(metaObject, CommonField.UPDATE_TIME.getProperty(), Date.class, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("MybatisPlus---更新update字段自动填充---begin---");
        // 修改
        this.strictUpdateFill(metaObject, CommonField.UPDATE_TIME.getProperty(), Date.class, new Date());
        this.strictUpdateFill(metaObject, CommonField.UPDATE_BY.getProperty(), String.class, BlackbeanRequestContextHolder.getUserId());
    }

}
